#include "history.h"
#include "ui_history.h"
#include "globalval.h"
#include <QJsonObject>


History::History(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::History)
{
    ui->setupUi(this);
    customPlot = new QCustomPlot;
    ui->dateTimeEditStart->setDateTime(QDateTime::currentDateTime());
    ui->dateTimeEditEnd->setDateTime(QDateTime::currentDateTime());
    QDateTime endTime = ui->dateTimeEditStart->dateTime().addSecs(3600);
    ui->dateTimeEditEnd->setDateTime(endTime);
    connect(this, SIGNAL(rejected()),this, SLOT(dialogClose()));
    connect(ui->pushButton, &QPushButton::clicked, this, &History::onButtonClicked);
    ui->horizontalLayout_4->addWidget(customPlot);
    customPlot->addGraph();
}

History::~History()
{
    delete ui;
}
QString History::getTitle() const
{
    return title;
}

void History::setTitle(const QString &value)
{
    QString text(value);
    ui->label->setText(text.append("历史数据记录"));
    setWindowTitle(text);
    title = value;
}
void History::onButtonClicked()
{
    // 获取开始和结束时间
    QDateTime startTime = ui->dateTimeEditStart->dateTime();
    QDateTime endTime = ui->dateTimeEditEnd->dateTime();

    qint64 startTimestamp = startTime.toMSecsSinceEpoch() / 1000;
    qint64 endTimestamp = endTime.toMSecsSinceEpoch() / 1000;

    QJsonObject jsonObject;
    jsonObject["type"] = 4;
    QJsonObject dataObject;
    dataObject["key"] = key;
    dataObject["limit"] = QJsonArray() << startTimestamp << endTimestamp;
    jsonObject["data"] = dataObject;

    QJsonDocument jsonDoc(jsonObject);
    QByteArray jsonByteArray = jsonDoc.toJson(QJsonDocument::Compact);

    QMQTT::Message message;
    message.setTopic("/app/data/down");
    message.setPayload(jsonByteArray);
    ui->horizontalLayout_4->addWidget(customPlot);
    GlobalVal::mqtt->publish(message);

}
int History::getKey() const
{
    return key;
}

void History::setKey(int value)
{
    key = value;
}
// 获取mqtt传来的数据
void History::dataUpSlot(QByteArray data)
{
    qDebug() << "history";
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
    if (jsonDoc.isNull()) {
        qDebug() << "Invalid JSON data";
        return;
    }
    QJsonObject jsonObject = jsonDoc.object();
    int type = jsonObject["type"].toInt();
    qDebug() << "Type:" << type;

    if (type != 4) {
        return;
    }

    QJsonArray dataArray = jsonObject["data"].toArray();
    // 获取数据渲染到页面的折线图
    QVector<double> keys;
    QVector<double> values;
    keys.reserve(dataArray.size());
    values.reserve(dataArray.size());

    for (const QJsonValue &value : dataArray) {
        QJsonObject dataObj = value.toObject();
        qint64 timestamp = dataObj["time"].toInt();
        double val = dataObj["val"].toString().toDouble();
        keys.push_back(timestamp);
        values.push_back(val);
    }
    if (!customPlot->graphCount()) {
        customPlot->addGraph();
    }

    QColor color(20 + 200 / 4.0, 70 * (1.6 / 4.0), 150, 150);
    customPlot->graph(0)->setLineStyle(QCPGraph::lsLine);
    customPlot->graph(0)->setPen(QPen(color.lighter(200)));
    customPlot->graph(0)->setData(keys, values);

    QSharedPointer<QCPAxisTickerDateTime> dateTicker(new QCPAxisTickerDateTime);
    dateTicker->setDateTimeFormat("yyyy-MM-dd hh:mm:ss");
    customPlot->xAxis->setTicker(dateTicker);
    customPlot->xAxis->setTickLabelRotation(30);
    customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
    customPlot->rescaleAxes();
    customPlot->replot();
}

void History::dialogClose()
{
    customPlot->clearGraphs();
    customPlot->replot();
}

